<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="null"
  >
    <a-spin :spinning="confirmLoading">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :xl="8" :lg="8" :md="12" :sm="24">
              <a-form-item label="工种筛选">
                <j-dict-select-tag
                  placeholder="请选择工种"
                  v-model="workTypeFilter"
                  dictCode="mes_work_type,work_type_name,id"
                  @change="loadAvailableTasks"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="12" :sm="24">
              <a-button type="primary" @click="loadAvailableTasks" icon="search">刷新</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-table
        :columns="columns"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        size="middle"
        bordered
      >
        <template slot="action" slot-scope="text, record">
          <a @click="handleClaimTask(record)" type="primary">领取任务</a>
        </template>

        <template slot="progress" slot-scope="text, record">
          <a-progress :percent="getTaskProgress(record)" size="small" />
        </template>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { mapGetters } from 'vuex'

export default {
  name: 'AvailableTasksModal',
  data() {
    return {
      title: '可领取任务',
      visible: false,
      confirmLoading: false,
      loading: false,
      workTypeFilter: '',
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onChange: (page, pageSize) => {
          this.pagination.current = page
          this.pagination.pageSize = pageSize
          this.loadAvailableTasks()
        },
        onShowSizeChange: (current, size) => {
          this.pagination.current = 1
          this.pagination.pageSize = size
          this.loadAvailableTasks()
        }
      },
      columns: [
        {
          title: '工种名称',
          dataIndex: 'workTypeName',
          align: 'center',
        },
        {
          title: '协作类型',
          dataIndex: 'collaborationType',
          align: 'center',
          customRender: (text) => {
            if (text === 0) {
              return '独立完成'
            } else if (text === 1) {
              return '协作完成'
            } else if (text === 2) {
              return '分段完成'
            }
          },
        },
        {
          title: '产品信息',
          dataIndex: 'productInfo',
          align: 'center',
        },
        {
          title: '任务数量',
          dataIndex: 'taskQuantity',
          align: 'center',
        },
        {
          title: '计划开始',
          dataIndex: 'planStartDate',
          align: 'center',
        },
        {
          title: '计划结束',
          dataIndex: 'planEndDate',
          align: 'center',
        },
        {
          title: '工序顺序',
          dataIndex: 'sequence',
          align: 'center',
          customRender: (text) => `第${text}道工序`,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        available: '/mes/task/available',
        claim: '/mes/task/claim',
      },
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    currentUser() {
      return this.userInfo || {}
    },
  },
  methods: {
    show() {
      this.visible = true
      this.loadAvailableTasks()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.dataSource = []
      this.workTypeFilter = ''
      this.pagination.current = 1
      this.pagination.total = 0
    },
    loadAvailableTasks() {
      this.loading = true
      let params = {
        employeeId: this.currentUser.id,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      }
      if (this.workTypeFilter) {
        params.workTypeId = this.workTypeFilter
      }

      getAction(this.url.available, params)
        .then((res) => {
          if (res.success) {
            // 确保 dataSource 始终是数组
            if (Array.isArray(res.result)) {
              this.dataSource = res.result
              this.pagination.total = res.result.length
            } else if (res.result && Array.isArray(res.result.records)) {
              // 处理分页数据结构
              this.dataSource = res.result.records
              this.pagination.total = res.result.total || 0
            } else if (res.result && typeof res.result === 'object') {
              // 如果是对象，尝试转换为数组
              this.dataSource = [res.result]
              this.pagination.total = 1
            } else {
              this.dataSource = []
              this.pagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
            this.dataSource = []
          }
        })
        .catch((error) => {
          console.error('加载可领取任务失败:', error)
          this.$message.error('加载可领取任务失败')
          this.dataSource = []
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleClaimTask(record) {
      const that = this
      this.$confirm({
        title: '确认领取',
        content: `是否确定领取工种"${record.workTypeName}"的任务？`,
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk: function () {
          let params = {
            taskId: record.id,
            employeeId: that.currentUser.id,
            remark: '',
          }

          postAction(that.url.claim, params).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadAvailableTasks() // 刷新列表
              that.$emit('ok') // 通知父组件刷新
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    getTaskProgress(record) {
      if (!record.taskQuantity || record.taskQuantity === 0) {
        return 0
      }
      const completed = record.completedQuantity || 0
      return Math.round((completed / record.taskQuantity) * 100)
    },
    handleOk() {
      this.close()
    },
    handleCancel() {
      this.close()
    },
  },
}
</script>
